<template>
  <div class="app-container bg-white">
    <!-- 页面内容 -->
    <div class="page-body">
      <el-form :inline="true" ref="queryFormRef" size="small" @submit.native.prevent>
        <el-form-item>
          <el-input size="small" placeholder="请输入部门名称" v-model.trim="queryName" maxlength="30" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button size="small" class="width_104" type="primary" @click="getPageDataList()">查询</el-button>
          <el-button size="small" class="width_104" @click="resetOption()">重置</el-button>
        </el-form-item>
      </el-form>
      <div>
        <el-button size="mini" type="success" icon="el-icon-document-add" @click="addDepartOption()" v-if="roleBtns.includes('sys:department:add') || $store.getters.isAdmin">新增部门</el-button>
        <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeDepartChildSelectOption()" v-if="roleBtns.includes('sys:department:del') || $store.getters.isAdmin">批量删除</el-button>
      </div>
      <el-table class="margin_top_20" ref="mutilTableRef" stripe default-expand-all :data="pageData" :header-cell-style="tableHeaderStyle" row-key="id" v-loading="loading" @selection-change="handleSelectionChange" @select="handleOneItem" @select-all="handleAllItem">
        <el-table-column type="selection" width="42" :selectable="checkSelectable"></el-table-column>
        <el-table-column prop="name" label="部门名称"></el-table-column>
        <el-table-column prop="num" label="成员数"></el-table-column>
        <el-table-column prop="isEnable" label="是否启用">
          <template slot-scope="scope">
            <el-switch @change="changeStatus($event, scope.row)" :value="scope.row.isEnable == 1" v-show="scope.row.id != '0'"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="360">
          <template slot-scope="scope">
            <div v-show="scope.row.id != '0'">
              <button class="my-btn my-btn--mini my-btn--primary plain" @click="pathManagePage(scope.row.id)" v-if="roleBtns.includes('sys:department:manage') || $store.getters.isAdmin" :disabled="scope.row.isEnable != 1">部门管理</button>
              <button class="my-btn my-btn--mini my-btn--primary plain" @click="addDepartChildOption(scope.row)" v-if="roleBtns.includes('sys:department:add') || $store.getters.isAdmin" :disabled="scope.row.isEnable != 1">添加子部门</button>
              <button class="my-btn my-btn--mini my-btn--primary plain" @click="updateDepartNameOption(scope.row)" v-if="roleBtns.includes('sys:department:update') || $store.getters.isAdmin" :disabled="scope.row.isEnable != 1">修改名称</button>
              <button class="my-btn my-btn--mini my-btn--danger plain" @click="removeDepartChildOption([scope.row.id])" v-if="roleBtns.includes('sys:department:del') || $store.getters.isAdmin">删除</button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <depart-form :visible.sync="isShowModel" :title="title" :depart="selectTreeData" :parentNode="selectParentNode" @update="getPageDataList()"></depart-form>

    <depart-name-form :visible.sync="isShowNameModel" :title="title" :node="selectNode" @update="getPageDataList()"></depart-name-form>
  </div>
</template>

<script>
import Setting from '@/settings';
import { mapGetters } from 'vuex';
import { GetDepartmentDataList, RemoveDepartmentItemData, UpdateDepartmentItemStatus } from '@/views/user-management/services/index';
import DepartForm from '@/views/user-management/components/departForm';
import DepartNameForm from '@/views/user-management/components/departNameForm';

export default {
  name: 'UserDepart',
  components: {
    DepartForm,
    DepartNameForm
  },
  data() {
    return {
      title: '',
      queryName: '',
      tableHeaderStyle: Setting.tableHeaderStyle,
      pageData: [],
      selectNode: null,
      selectTreeData: [],
      selectParentNode: [],
      loading: false,
      isShowModel: false,
      isShowNameModel: false,
      isEditMode: false,
      multipleSelection: []
    }
  },
  computed: {
    ...mapGetters([
        'roleBtns'
    ])
  },
  activated() {
    this.getPageDataList();
  },
  created() {
    this.getPageDataList();
  },
  methods: {
    handleAllItem(selection) {
      if (selection && selection.length) {
        this.$refs.mutilTableRef.clearSelection();
      } else {
        this.toggleRowSelection(this.pageData, true);
      }
    },
    handleOneItem(selection, row) {
      const newselection = JSON.parse(JSON.stringify(selection));
      const finder = newselection.find(item => item.id == row.id)
      if (finder) {
        this.toggleRowSelection([row], true);
      } else {
        this.toggleRowSelection([row], false);
      }
    },
    toggleRowSelection(rows, state) {
      for (let i = 0; i < rows.length; i++) {
        let row = rows[i];
        if (row.id != '0') {
          this.$refs.mutilTableRef.toggleRowSelection(row, state);
        }
        if (row.children && row.children.length) {
          this.toggleRowSelection(row.children, state);
        }
      }
    },
    checkSelectable(row) {
      if (row.id == '0') {
        return 0;
      } else {
        return 1;
      }
    },
    pathManagePage(departId) {
      this.$router.push({
        name: 'UserDepartManage',
        query: { departId }
      })
    },
    changeStatus(event, rowData) {
      if (event) {
        this.loading = true;
        UpdateDepartmentItemStatus({ id: rowData.id })
        .finally(() => this.loading = false)
        .then(data => {
          if (data.code == 200) {
            this.$message.success('启用成功!');
            this.getPageDataList();
          } else {
            this.$message.error('启用失败!');
          }
        })
        .catch(error => {
          this.$message.error(error);
        })
        return;
      }
      this.$confirm('此操作将禁用该部门，部门被禁用后，部门下所有子部门及成员都被禁用，成员无法登录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false,
        closeOnPressEscape: false,
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true;
            UpdateDepartmentItemStatus({ id: rowData.id })
            .then(data => {
              instance.confirmButtonLoading = false;
              if (data.code == 200) {
                this.$message.success('禁用成功!');
                this.getPageDataList();
                done();
              } else {
                this.$message.success('禁用失败!');
              }
            })
            .catch(error => {
              instance.confirmButtonLoading = false;
            })
          } else {
            done();
          }
        }
      });
    },
    removeDepartChildSelectOption() {
      if (!this.multipleSelection || !this.multipleSelection.length) {
        this.$message.warning('请选择需要删除的部门!');
        return;
      }
      this.removeDepartChildOption(this.multipleSelection.map(item => item.id));
    },
    removeDepartChildOption(nodeIds) {
      this.$confirm('此操作将永久删除该部门, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false,
        closeOnPressEscape: false,
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true;
            // instance.confirmButtonText = '加载中...';
            RemoveDepartmentItemData({ ids: nodeIds })
            .then(data => {
              instance.confirmButtonLoading = false;
              if (data.code == 200) {
                this.$message.success('删除成功!');
                this.getPageDataList();
                done();
              } else {
                this.$message.success('删除失败!');
              }
            })
            .catch(error => {
              instance.confirmButtonLoading = false;
            })
          } else {
            done();
          }
        }
      });
    },
    updateDepartNameOption(node) {
      this.title = '修改名称';
      this.isShowNameModel = true;
      this.selectNode = node;
    },
    addDepartOption() {
      this.selectParentNode = [];
      this.title = '新增部门';
      this.isShowModel = true;
    },
    addDepartChildOption(node) {
      this.selectParentNode = [];
      if (node.parentId) {
        this.selectParentNode = this.deepTreeData(node.parentId, this.pageData);
      }
      this.selectParentNode.push(node);
      this.title = '添加子部门';
      this.isShowModel = true;
    },
    getPageDataList() {
      this.loading = true;
      GetDepartmentDataList({
        proId: 4, // 项目id 默认4
        depId: 0, // 部门id  如果需要查所有的填写0  其他填写要查的部门id
        // isEnable: 1, // 0禁用1启用  根据需要自行查  下拉选择用户角色时的部门传1  部门列表不用传默认查所有
        // parentId: 0, // 只需要一级父类时传0  只获取顶级权限一层 对应depid需要传0
        name: this.queryName
      })
      .then(res => {
        this.loading = false;
        if (res.code == 200) {
          this.pageData = res.data;

          this.selectTreeData = JSON.parse(JSON.stringify(res.data));
        }
      })
      .catch(error => {
        this.loading = false;
      })
    },
    resetOption() {
      this.queryName = '';
      this.getPageDataList();
    },
    // table全选按钮操作
    handleSelectionChange(selectlist) {
      this.multipleSelection = selectlist;
    },
    // 深层递归返回选中的父级id
    deepTreeData(id, list) {
      let nodes = [];
      let myDeep = (parentId, childlist) => {
        if (!childlist || !childlist.length) return; 
        childlist.forEach(child => {
          if (child.id == parentId) {
            nodes.unshift(child);
            myDeep(child.parentId, list);
          } else {
            if (child.children && child.children.length) {
              myDeep(parentId, child.children);
            }
          }
        })
      }

      myDeep(id, list);
      return nodes;
    }
  }
}
</script>

<style lang="scss" scoped>
.width_104 {
  width: 104px;
}
</style>
